package Admin;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;

import javax.swing.AbstractButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import Admin.Account.MyItemListener;
import GroupClass.ConnectRMI;
import Project_etow.EtowInterface;

public class BillPayment extends javax.swing.JDialog {

    ConnectRMI connectRMI = new ConnectRMI();
	private DefaultTableModel dtm; 
	
	private String billpaysec , billpaywas, billpayclean, billpaymaint, billpaypark, idbillpay;
    public BillPayment(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
    	setTitle("Bill Payment");
        jScrollPane1 = new javax.swing.JScrollPane();
        tbdulieu = new javax.swing.JTable();
        btinsert = new javax.swing.JButton();
        btupdate = new javax.swing.JButton();
        btdelete = new javax.swing.JButton();
        btexit = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setLocation(350 , 150);
        Object colNames[] = {"", "Security","WashingRooms","CleanBuildingGlasses","MaintenanceElevator","AmountOfParking",""};  
  	  	Object[][] data = {};  
  	  	
  	  	
  	  	dtm = new DefaultTableModel(data,colNames);  
  	  	tbdulieu = new JTable(dtm);
	    tbdulieu.getColumnModel().getColumn(0).setResizable(false);
	    tbdulieu.getTableHeader().setReorderingAllowed(false);
	  	tbdulieu.getColumnModel().getColumn(0).setMinWidth(75);
	  	
	  	tbdulieu.getColumnModel().getColumn(6).setMaxWidth(0);


	  	
  	  try {				 
  		Registry registry = LocateRegistry.getRegistry(connectRMI.host, connectRMI.port);
  		EtowInterface obj=(EtowInterface)registry.lookup(connectRMI.regis);
  			
  		List<GroupClass.BillPaymentClass> x =obj.ShowAllBillPayment();
  			
  		
  		for(GroupClass.BillPaymentClass d:x) {
  		
        	 billpaysec = d.getBillPaymetSecurity();
        	 billpaywas = d.getBillPaymetWashingRooms();
        	 billpayclean = d.getBillPaymetCleanBuildingGlasses();
        	 billpaymaint = d.getBillPaymetMaintenanceElevator();
        	 billpaypark = d.getBillPaymetAmountOfParking();
        	 idbillpay = d.getBillPaymetid();
        	
        
  	    dtm.addRow(new Object[]{new Boolean(false),billpaysec,billpaywas,billpayclean,billpaymaint,billpaypark,idbillpay});
  		}									
  			
  		}catch (Exception ex) {
  			ex.printStackTrace();
  		}	  	    
  		
  		TableColumn tc = tbdulieu.getColumnModel().getColumn(0);  
  	    tc.setCellEditor(tbdulieu.getDefaultEditor(Boolean.class));  
  	    tc.setCellRenderer(tbdulieu.getDefaultRenderer(Boolean.class));  
  	    tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
  	    
  	    
  	  	tbdulieu.addMouseListener(new MouseAdapter()
                {
  	  	@Override
                public void mouseClicked(MouseEvent e) {
                        e.consume();
                        int row = tbdulieu.getSelectedRow();
                        billpaysec = tbdulieu.getValueAt(row, 1).toString();
                        billpaywas = tbdulieu.getValueAt(row, 2).toString();
                        billpayclean = tbdulieu.getValueAt(row, 3).toString();
                        billpaymaint = tbdulieu.getValueAt(row, 4).toString();
                        billpaypark = tbdulieu.getValueAt(row, 5).toString();
                        idbillpay = tbdulieu.getValueAt(row, 6).toString();



                }
                });
  	    
        jScrollPane1.setViewportView(tbdulieu);

        btinsert.setText("Insert");
        btinsert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btinsertActionPerformed(evt);
            }
        });

        btupdate.setText("Update");
        btupdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btupdateActionPerformed(evt);
            }
        });

        btdelete.setText("Delete");
        btdelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btdeleteActionPerformed(evt);
            }
        });

        btexit.setText("Exit");
        btexit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btexitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btinsert)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btupdate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btdelete)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 122, Short.MAX_VALUE)
                .addComponent(btexit)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btinsert)
                    .addComponent(btupdate)
                    .addComponent(btdelete)
                    .addComponent(btexit))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>

    private void btinsertActionPerformed(java.awt.event.ActionEvent evt) {
        InsertBillPayment isb = new InsertBillPayment(null, true);
        isb.setCheckinviinsrt("ok");
        isb.setVisible(true);
        while (isb.isVisible() != true) {
                if (isb.getCheckinviinsrt().equals("close")) {
                        reloadtable();
                        break;
                }
        }
        
    }

    private void btupdateActionPerformed(java.awt.event.ActionEvent evt) {
        for (int j = 0; j < tbdulieu.getRowCount(); j++) {
            
            if (tbdulieu.getValueAt(j, 0).toString() == "true") {
              billpaysec = tbdulieu.getValueAt(j, 1).toString();
              billpaywas = tbdulieu.getValueAt(j, 2).toString();
              billpayclean = tbdulieu.getValueAt(j, 3).toString();
              billpaymaint = tbdulieu.getValueAt(j, 4).toString();
              billpaypark = tbdulieu.getValueAt(j, 5).toString();
              idbillpay = tbdulieu.getValueAt(j, 6).toString();
                UpdateBillPayment upbillp = new UpdateBillPayment(null, true,billpaysec, billpaywas, billpayclean, billpaymaint, billpaypark, idbillpay);
                upbillp.setVisible(true);
            }
            
        }
       
        
    }

    private void btdeleteActionPerformed(java.awt.event.ActionEvent evt) {
        String result = "";
        int i = JOptionPane.showConfirmDialog(null,
                        "Neu Ban Da Chac Chan Hay Chon Ok", null,
                        JOptionPane.YES_NO_OPTION);
        if (i == JOptionPane.YES_OPTION) {
                EtowInterface obj = null;
                Registry registry;
                try {
                        registry = LocateRegistry.getRegistry(connectRMI.host, connectRMI.port);
                        obj = (EtowInterface) registry.lookup(connectRMI.regis);
                      
                        for (int j = 0; j < tbdulieu.getRowCount(); j++) {
                                if (tbdulieu.getValueAt(j, 0).toString() == "true") {
                                        try {
                                                
                                                result = obj.DeleteBillPayment(tbdulieu.getValueAt(j, 6).toString());
                                                if(result != "Ok")
                                                {
                                                        JOptionPane.showMessageDialog(null, "This BillPayment is using in Bill , Can you edit or delete this bill");
                                                }
                                                
                                        } catch (RemoteException e) {
                                                e.printStackTrace();
                                        }
                                }
                        }

                        reloadtable();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
    }

    private void btexitActionPerformed(java.awt.event.ActionEvent evt) {
        this.setVisible(false);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BillPayment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BillPayment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BillPayment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BillPayment.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                BillPayment dialog = new BillPayment(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btdelete;
    private javax.swing.JButton btexit;
    private javax.swing.JButton btinsert;
    private javax.swing.JButton btupdate;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbdulieu;
    
    class MyItemListener implements ItemListener  
    {  
     public void itemStateChanged(ItemEvent e) {  
        Object source = e.getSource();  
        if (source instanceof AbstractButton == false) return;  
        boolean checked = e.getStateChange() == ItemEvent.SELECTED;  
        for(int x = 0, y = tbdulieu.getRowCount(); x < y; x++)  
        {  
        	tbdulieu.setValueAt(new Boolean(checked),x,0);  
        }  
      }  
    }
    
    public void reloadtable() {

        while (tbdulieu.getRowCount() != 0) {
                dtm.removeRow(0);
        }

        try {
                Registry registry = LocateRegistry.getRegistry(connectRMI.host, connectRMI.port);
                EtowInterface obj = (EtowInterface) registry.lookup(connectRMI.regis);

List<GroupClass.BillPaymentClass> x =obj.ShowAllBillPayment();
                        
                
                for(GroupClass.BillPaymentClass d:x) {
                
                 billpaysec = d.getBillPaymetSecurity();
                 billpaywas = d.getBillPaymetWashingRooms();
                 billpayclean = d.getBillPaymetCleanBuildingGlasses();
                 billpaymaint = d.getBillPaymetMaintenanceElevator();
                 billpaypark = d.getBillPaymetAmountOfParking();
                 idbillpay = d.getBillPaymetid();
                
        
            dtm.addRow(new Object[]{new Boolean(false),billpaysec,billpaywas,billpayclean,billpaymaint,billpaypark,idbillpay});
                }

        } catch (Exception ex) {
                ex.printStackTrace();
        }
}
    
}
